<template>
  <div class="box">
    <div class="innerBox">
      <div class="left">
        <div class="content">
          <el-tabs v-model="activeName">
            <el-tab-pane label="题目" name="one"></el-tab-pane>
            <el-tab-pane label="答案" name="two"></el-tab-pane>
          </el-tabs>
          <template v-if="online">
            <div style="overflow-y: auto" v-if="activeName=='one'" v-html="detail.itemBank&&detail.itemBank.testItemContent">
            </div>
            <div style="overflow-y: auto"  v-if="activeName=='two'" v-html="detail.answer">
            </div>
          </template>
          <template v-else>
            <el-image v-if="activeName=='one'" :preview-src-list="[detail.questionPicture,detail.answerPicture]"
                      :src="detail.questionPicture" alt="" fit="contain"></el-image>
            <el-image v-if="activeName=='two'" :preview-src-list="[detail.questionPicture,detail.answerPicture]"
                      :src="detail.answerPicture" alt="" fit="contain"></el-image>
          </template>
        </div>
      </div>
      <div class="right">
        <div class="top">

          <el-form ref="form" :model="form" class="elForm" inline label-width="80px">
            <div>
              <el-form-item label="考生">
                <el-select
                  v-if="!online"
                  v-model="form.studentId"
                  :loading="loading"
                  :remote-method="remoteMethod"
                  filterable
                  placeholder="请输入关键词"
                  remote
                  reserve-keyword>
                  <el-option
                    v-for="item in userList"
                    :key="item.userId"
                    :label="item.nickName"
                    :value="item.userId"
                  >
                  </el-option>
                </el-select>
                <div v-else>{{studentDetail.nickName}}</div>
              </el-form-item>
              <el-form-item label="题目">
                <el-radio-group v-model="form.result">
                  <el-radio label="正确">正确</el-radio>
                  <el-radio label="错误">错误</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>

            <el-tabs v-model="labelClass">
              <el-tab-pane label="计算" name="js"></el-tab-pane>
              <el-tab-pane label="条件翻译" name="tj"></el-tab-pane>
              <el-tab-pane label="题型辨识" name="tx"></el-tab-pane>
            </el-tabs>

            <div style="overflow: auto;height: 100%">

              <div v-show="labelClass=='tx'" class="item">
                <div class="content">
                  <div v-for="item in questionType" class="itemInner">
                    <div>
                      {{ item.name }}
                    </div>
                    <div>
                      <el-radio v-model="item.isNo" label="yes"
                      >选项没问题了
                      </el-radio
                      >
                      <el-radio v-model="item.isNo" label="no"
                      >我对这个选项有疑问
                      </el-radio
                      >
                    </div>
                  </div>
                  <el-button type="text" @click="getQuestionType(5)"
                  ><i class="el-icon-circle-plus"></i> 添加选项
                  </el-button
                  >
                </div>
              </div>
              <div v-show="labelClass=='tj'" class="item">
                <div class="content">
                  <div v-for="item in condition" class="itemInner">
                    <div>
                      {{ item.name }}
                    </div>
                    <div>
                      <el-radio v-model="item.isNo" label="yes"
                      >选项没问题了
                      </el-radio
                      >
                      <el-radio v-model="item.isNo" label="no"
                      >我对这个选项有疑问
                      </el-radio
                      >
                    </div>
                  </div>
                  <el-button type="text" @click="getQuestionType(8)"
                  ><i class="el-icon-circle-plus"></i> 添加选项
                  </el-button
                  >
                </div>
              </div>
              <div v-show="labelClass=='js'" class="item">
                <div class="content">
                  <div v-for="item in count" class="itemInner">
                    <div>
                      {{ item.name }}
                    </div>
                    <div>
                      <el-radio v-model="item.isNo" label="yes"
                      >选项没问题了
                      </el-radio
                      >
                      <el-radio v-model="item.isNo" label="no"
                      >我对这个选项有疑问
                      </el-radio
                      >
                    </div>
                  </div>
                  <el-button type="text" @click="getQuestionType(9)"
                  ><i class="el-icon-circle-plus"></i> 添加选项
                  </el-button
                  >
                </div>
              </div>
            </div>


          </el-form>
        </div>
        <div class="bottom">
          <div id="bottomImage" style="text-align: center;margin-top: 20px ">
            <el-image v-if="upImg" :src="upImg" style="height: 150px;width: 150px"></el-image>


            <el-upload
              v-else
              :action="baseUrl + '/common/upload'"
              :headers="{
                  Authorization: `Bearer  ${this.$store.state.user.token}`,
                }"
              :on-success="(res)=>onSuccess(res,'ls')"
              class="upload-demo"
              drag
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </div>
          <div class="teacher">
            <el-input v-model="form.teacherRemarks" :rows="4" placeholder="请输入内容" type="textarea"></el-input>
            <div>
              <el-button @click="submit">提交</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- ---------------- -->

    <el-dialog
      :visible.sync="visibles"
      class="dialogAddTree"
      title="提示"
      width="50vw"
    >
      <div>
        <el-tag
          v-for="(tag, index) in temporaryArray"
          :key="tag.labelId"
          :disable-transitions="false"
          closable
          style="margin-right: 15px; margin-bottom: 10px"
          @close="handleClose(tag)"
        >
          {{ tag.name }}
        </el-tag>
      </div>
      <div style="height: 100%">
        <div class="diaRight">
          <el-tree
            :data="typeTreeData"
            :default-expand-all="false"
            :highlight-current="true"
            :props="defaultProps"
          >
            <span slot-scope="{ node, data }" class="custom-tree-node">
              <span style="margin-right: 15px">{{ node.label }}</span>
              <span class="label">
                <el-button
                  icon="el-icon-circle-plus-outline"
                  size="mini"
                  type="text"
                  @click.stop="() => append(node, data)"
                >
                </el-button>
              </span>
            </span>
          </el-tree>
        </div>
      </div>
    </el-dialog>
    <!-- ---------------- -->

    <!-- 隐藏的文件输入元素 -->
    <input
      ref="fileInput"
      style="display: none"
      type="file"
      @change="handleFileChange"
    />


    <!--    学情分析图片-->
    <el-dialog
      :visible.sync="tage"
      class="dialogAddTree1"
      title="提示"
      width="700px"
    >
      <el-form style="text-align: center">
        <el-form-item label="选择生成试卷标签">
          <el-select
            v-model="form.topicTag"
            placeholder="请选择"
            popper-class="mediaPopu"
            style="min-width: 300px"
          >
            <el-option
              v-for="item in options"
              :key="item.labelId"
              :label="item.name"
              :value="item.labelId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="输入生成题目数量">
          <el-input :min="1" style="width: 300px" v-model="form.num" type="number"></el-input>
        </el-form-item>
        <el-form-item label="学情分析图片来源">
          <el-radio-group v-model="photoType" >
            <el-radio label="one">题目</el-radio>
            <el-radio label="two">答案</el-radio>
            <el-radio label="there">老师批注</el-radio>
            <el-radio label="four">上传</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="上传用于学情分析的图片" >-->
        <el-form-item label="上传用于学情分析的图片" v-if="photoType=='four'">


          <el-image v-if="form.learnAnalyzePictures!=''" :src="form.learnAnalyzePictures" fit="contain"
                    style="height: 200px;width: 200px"></el-image>
          <el-upload
            v-else
            :action="baseUrl + '/common/upload'"
            :auto-upload="true"
            :on-success="(res)=>onSuccess(res,'xq')"
            list-type="picture-card">
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>

        </el-form-item>

        <el-form-item>
          <el-button @click="generateTestPapers">生成试卷</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    学情分析图片-->


  </div>
</template>
<script>
import {
  base64ToUrl,
  getOnlinePaper,
  getPaper,
  getUserList,
  teacherMarkPaper,
  teacherMarkPaperOline
} from "@/api/markingPapers";
import {mapGetters} from "vuex";
import {listTypes} from "@/api/questionBank/type";

export default {
  data() {
    return {
      detail: {},
      activeName: 'one',
      form: {
        teacherRemarks: '',
        teacherPicture: '',//老师的图片
        studentId: '',
        result: '',
        topicTag: '',
        learnAnalyzePictures: '',
        num:1

      },
      userList: [],
      labelClass: 'js',

      condition: [],
      index: null,
      typeTreeData: [],
      visibles: false,
      temporaryArray: null,
      defaultProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      questionType: [],
      count: [],
      upImg: null,
      tage: false,
      //弹框学情分析
      learnAnalyzePictures: '',
      options: [],
      loading: false,
      online: false,
      studentDetail:{},
      photoType:'four'
    }
  },
  mounted() {
    this.getUserList()

    if (this.$route.query.type == 'onLine') {
      this.online = true
      this.getOnlineDetail()
      this.studentDetail=JSON.parse(localStorage.getItem('studentDetail'))
      this.form.studentId=this.studentDetail.userId
    } else {

      this.getListData()
    }


    //粘贴图片
    let that = this;

    let imgBottom = document.querySelector('#bottomImage')

    imgBottom.addEventListener("paste", function (e) {

      e.stopPropagation();
      if (e.clipboardData && e.clipboardData.items) {
        let items = e.clipboardData.items;
        if (items) {
          items = Array.prototype.filter.call(items, function (element) {
            return element.type.indexOf("image") >= 0;
          });
          Array.prototype.forEach.call(items, function (item) {
            var blob = item.getAsFile();

            var rdr = new FileReader();
            rdr.onloadend = function () {

              that.upImg = rdr.result;
              that.uploadFile(rdr.result)
            };

            rdr.readAsDataURL(blob);
          });
        }
      }

    });
    let img = document.querySelector("#imgRight");
  }
  ,
  computed: {
    ...mapGetters(["baseUrl", 'userId']),
  },
  updated() {
    //判断是否初始配置，若无则配置。
    if (!this.mathJax.isMathjaxConfig.bool) {
      this.mathJax.initMathjaxConfig();
    }
    this.$nextTick((_) => {
      //传入组件id，让组件被MathJax渲染
      this.mathJax.MathQueue("questionList-page");
    });
  },

  watch: {
    visibles: function (n, o) {
      if (!n) {
        this.temporaryArray = [];
      }
    },
    photoType:function (n,o){
      if(n=='one'){
        this.form.learnAnalyzePictures=this.detail.questionPicture
      }
      if(n=='two'){
        this.form.learnAnalyzePictures=this.detail.answerPicture
      }
      if(n=='there'){
        // this.form.learnAnalyzePictures=this.upImg
        this.form.learnAnalyzePictures=this.form.teacherPicture

      }
      if(n=='four'){
        this.form.learnAnalyzePictures=''
      }
    },

  },
  methods: {
    getListData() {
      getPaper(this.$route.query.id).then(res => {
        this.detail = res.data
      })
    },
    getOnlineDetail() {
      getOnlinePaper(this.$route.query.id).then(res => {
        this.detail = res.data
      })
    },
    async getUserList() {
      await getUserList().then((res) => {
        if (res.code == 200) {
          this.userList = res.rows;
        }
      });
    },
    //获取标签
    getQuestionType(val, arr) {
      listTypes({reserve3: val}).then((Response) => {
        if (Response.code == 200) {
          this.index = val;
          this.typeTreeData = Response.rows;
          this.visibles = true;
          if (this.index == 5) {
            this.temporaryArray = JSON.parse(JSON.stringify(this.questionType));
          }
          if (this.index == 8) {
            this.temporaryArray = JSON.parse(JSON.stringify(this.condition));
          }
          if (this.index == 9) {
            this.temporaryArray = JSON.parse(JSON.stringify(this.count));
          }
        }
      });
    },
    //删除标签
    handleClose(tag) {
      this.temporaryArray.splice(this.temporaryArray.indexOf(tag), 1);

      if (this.index == 5) {
        this.questionType.splice(this.questionType.indexOf(tag), 1);
      }
      if (this.index == 8) {
        this.condition.splice(this.condition.indexOf(tag), 1);
      }
      if (this.index == 9) {
        this.count.splice(this.count.indexOf(tag), 1);
      }
    },
    //从树状图添加
    append(node, data) {
      let obj = {
        name: data.name,
        labelId: data.id,
        isNo: "yes",
      };

      if (this.index == 5) {
        // 使用 find 方法检查数组中是否已存在具有相同属性的对象
        const existingObj = this.questionType.find(
          (item) => item.name === obj.name && item.labelId === obj.labelId
        );
        if (existingObj) {
          this.$message.warning("不能添加重复标签");
          return;
        }
        this.questionType.push(obj);
      }
      if (this.index == 8) {
        // 使用 find 方法检查数组中是否已存在具有相同属性的对象
        const existingObj = this.condition.find(
          (item) => item.name === obj.name && item.labelId === obj.labelId
        );
        if (existingObj) {
          this.$message.warning("不能添加重复标签");
          return;
        }
        this.condition.push(obj);
      }
      if (this.index == 9) {
        // 使用 find 方法检查数组中是否已存在具有相同属性的对象
        const existingObj = this.count.find(
          (item) => item.name === obj.name && item.labelId === obj.labelId
        );
        if (existingObj) {
          this.$message.warning("不能添加重复标签");
          return;
        }
        this.count.push(obj);
      }
      this.temporaryArray.push(obj);
    },
    submit() {

      if (this.form.teacherPicture == "") {
        this.$message.warning("请上传图片");
        return;
      }
      if (this.questionType.length == 0) {
        this.$message.warning("请选择题型辨识标签");
        return;
      }
      if (this.condition.length == 0) {
        this.$message.warning("请选择条件翻译标签");
        return;
      }
      if (this.count.length == 0) {
        this.$message.warning("请选择计算标签");
        return;
      }

      if (this.form.studentId == '') {
        this.$message.warning("学生不能为空");
        return;
      }
      if (this.form.result == '') {
        this.$message.warning("题目正误不能为空");
        return;
      }


      let jobTestPaperAndLabelList = [...this.questionType, ...this.condition, ...this.count];
      this.options = jobTestPaperAndLabelList;
      this.form['reserve6'] = Number(this.$route.query.id)
      this.form['teacherId'] = this.userId
      this.form['jobTestPaperAndLabelList'] = jobTestPaperAndLabelList

      console.log(this.form)

      this.tage = true


    },
    handleFileChange(event) {
      let _this = this;

      // 获取用户选择的文件
      const file = event.target.files[0];
      if (file) {
        // 在这里处理文件，例如上传文件
        // console.log(file);
        const reader = new FileReader();

        reader.onloadend = function () {
          const base64data = reader.result;
          // console.log(base64data);
          _this.upImg = base64data;

        };
        reader.readAsDataURL(file);
      }
    },
    //赋值图片上传
    uploadFile(file) {

      let formData = new FormData()


      formData.append('base64', file)
      base64ToUrl(formData).then(res => {
        console.log(res, 'base64')
        this.form.teacherPicture = res.url
      })
    },
    //文件组件
    onSuccess(response, type) {
      if (type == 'ls') {

        this.upImg = response.url
        this.form.teacherPicture = response.url
      }
      if (type == 'xq') {
        this.form.learnAnalyzePictures = response.url
      }

    },
    //提交阅卷
    //生成试卷
    generateTestPapers() {
      if (this.form.topicTag == "") {
        this.$message.warning("请选择要生成试题的标签");
        return;
      }
      if (this.form.num <1) {
        this.$message.warning("题目数量不能小于1");
        return;
      }
      if (this.form.learnAnalyzePictures=='') {
        this.$message.warning("学情分析的照片不能为空");
        return;
      }
      console.log(this.form)

      if(this.$route.query.type=='onLine'){

        teacherMarkPaperOline(this.form).then(res => {
          if (res.code == 200) {
            this.$message.success("保存成功");
            this.$router.back(1)
          }
        })
      }else{
        this.form['jobTestPaperId']=this.$route.query.id
        teacherMarkPaper(this.form).then(res => {
          if (res.code == 200) {
            this.$message.success("保存成功");
            this.$router.back(1)
          }
        })

      }


    },
    //级联搜索
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        let obj = {
          nickName: query,
          // userName: query,
        }
        getUserList(obj).then((res) => {
          if (res.code == 200) {
            this.loading = false;
            this.userList = res.rows;
          }
        });

        // setTimeout(() => {
        //   this.loading = false;
        //   this.options = this.list.filter(item => {
        //     return item.label.toLowerCase()
        //       .indexOf(query.toLowerCase()) > -1;
        //   });
        // }, 200);
      } else {
        this.getUserList()
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  height: 100%;
  padding: 10px;
  min-width: 1000px;

  .innerBox {
    border: 1px solid #000;
    height: 100%;
    display: flex;

    > .left {
      flex: 1;
      border-right: 1px solid #000;
      padding: 10px;
      box-sizing: border-box;

      > .content {
        height: 100%;
        display: flex;
        flex-direction: column;

        .el-image {
          margin: 0 auto;
          flex: 1;
        }
      }


    }

    > .right {
      flex: 1;
      display: flex;
      flex-direction: column;

      > .top {
        border-bottom: 1px solid #000;
        flex: 1;
        min-height: 400px;
        padding: 10px;


        .item {
          min-height: 100px;
          border: #f1f3f8 1px solid;
          margin-bottom: 15px;
          padding: 5px;
          font-size: 14px;

          > div:nth-of-type(1) {
            font-size: 16px;
          }

          > .content {
            .itemInner {
              padding: 10px 0;
              display: flex;
              flex-direction: column;
              border-bottom: 1px #f1f3f8 solid;

              > div:nth-of-type(1) {
                align-self: flex-start;
                margin-bottom: 10px;
              }

              > div:nth-of-type(2) {
                ::v-deep .el-radio__label {
                  font-size: 12px;
                }
              }
            }
          }
        }
      }

      > .bottom {
        padding: 10px;
        flex: 1;

        > .title {
          font-size: 16px;
          font-weight: bold;
          text-align: center;
        }

      }

      .teacher {
        margin-top: 20px;
        display: flex;
        align-items: center;
        padding: 0 20px;

        > .el-textarea {
          flex: 1;
        }

        > div {
          width: 100px;
          text-align: center;
        }
      }
    }

  }
}

.elForm {
  height: calc(100% - 130px);

  > div:nth-of-type(1) {
    margin-top: 20px;
  }

  //
  //
  //.el-form-item {
  //  width: 40%;
  //  text-align: center;
  //}
}


.dialogAddTree {
  ::v-deep .el-dialog {
    min-width: 1070px;
  }

  .diaRight {
    flex: 1;
    overflow: auto;
    width: 100%;
    max-height: 800px;
    position: relative;

    .el-tree {
      width: max-content;
    }

    .label {
      display: none !important;
    }

    .custom-tree-node {
      display: flex;
      align-items: center;
    }

    .is-current {
      > .el-tree-node__content {
        .label {
          display: block !important;
        }
      }
    }
  }
}

</style>
